//
//  SearchViewController.m
//  何五路
//
//  Created by _ADY on 15/6/5.
//  Copyright (c) 2015年 _ADY. All rights reserved.
//

#import "SearchViewController.h"
#import "GoodsDetailsViewController.h"
@interface SearchViewController ()

@end
#define topButtonTag 100
@implementation SearchViewController
@synthesize mTableView,fListArray,sxListArray,stringId,stringText;

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = YES;

    for (UIView *subView in [[searchBar.subviews objectAtIndex:0] subviews])
    {
        if([subView isKindOfClass:[UIButton class]]){
            [(UIButton*)subView setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
    
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = YES;
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    searchBar.showsCancelButton = NO;
    return YES;
}

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text NS_AVAILABLE_IOS(3_0)
{
    return YES;
}
#pragma mark  UISearchBar 响应事件
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [mTableView.header beginRefreshing];
    [searchBar resignFirstResponder];
    searchBar.showsCancelButton = NO;
    
}
- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
    [searchBar resignFirstResponder];
    searchBar.showsCancelButton = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [m_searchBar resignFirstResponder];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = bgColor;
    
    orderBy = 17;
    m_searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(100, 0, 100, 41)];
    m_searchBar.delegate = self;
    m_searchBar.backgroundColor = [UIColor clearColor];
    m_searchBar.placeholder = (@"搜索所有商品");
    m_searchBar.keyboardType =  UIKeyboardTypeDefault;
    [self.navigationItem setTitleView:m_searchBar];
//    [m_searchBar becomeFirstResponder];
    for (UIView *view in m_searchBar.subviews) {//去除背景色
        
        if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
            [[view.subviews objectAtIndex:0] removeFromSuperview];
            break;
        }
    }
    
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, screenMySize.size.width, screenMySize.size.height-40)];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:mTableView];
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];//清除多余分割线
    [mTableView setTableFooterView:v];
    
    __weak __typeof(self) weakSelf = self;
    
    mTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadNewData];
    }];
    mTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    pageForNumber = 1;
    fListArray = [[NSMutableArray alloc] init];
    sxListArray = [[NSMutableArray alloc] init];
    
    [self barView];
    
    [mTableView.header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [BDModel cleanAllArchiveFile];
    if ([stringText isEqualToString:@"1"])
    {
        [m_searchBar becomeFirstResponder];
        stringText = @"0";
    }
//    else
//        [mTableView.header beginRefreshing];
        
}
- (void)loadNewData
{
    pageForNumber = 1;
    [self upDateTableView];
}
- (void)loadMoreData
{
    pageForNumber++;
    [self upDateTableView];
}

-(void)upDateTableView
{
    if ((pageForNumber-1)*itemLabel <= [fListArray count]||pageForNumber ==1)
    {
        NSMutableDictionary *postDic = [[NSMutableDictionary alloc] init];
        [postDic setObject:@"0" forKey:@"shopId"];
        [postDic setObject:@"0" forKey:@"categoryId"];
        [postDic setObject:@"" forKey:@"searchKeyWord"];
        if (m_searchBar.text.length == 0)
            [postDic setObject:@"" forKey:@"subSearchKeyWord"];
        else
            [postDic setObject:m_searchBar.text forKey:@"subSearchKeyWord"];
        [postDic setObject:[NSNumber numberWithInt:pageForNumber] forKey:@"pageNumber"];
        [postDic setObject:[NSNumber numberWithInt:itemLabel] forKey:@"pageSize"];
        [postDic setObject:[NSNumber numberWithInt:orderBy] forKey:@"orderBy"];
        
        NSString *AttID = @"";
        NSMutableArray *array = [screenItem unarchiveWithKey:@"screenDicYes"];
        for (NSDictionary *dic1 in  array)
        {
            if (![[NSString stringWithFormat:@"%@",[dic1 objectForKey:@"OptionId"]] isEqualToString:@"0"])
            {
                if (AttID.length == 0) {
                    AttID = [NSString stringWithFormat:@"%@",[dic1 objectForKey:@"OptionId"]];
                }
                else
                    AttID =  [NSString stringWithFormat:@"%@;%@",AttID,[dic1 objectForKey:@"OptionId"]];
            }

        }
        if (stringId != nil)
        {
            if (AttID.length == 0) {
                AttID = [NSString stringWithFormat:@"%@",stringId];
            }
            else
                AttID =  [NSString stringWithFormat:@"%@;%@",AttID,stringId];
            stringId = nil;
        }
        NSLog(@"%@",AttID);
        [postDic setObject:AttID forKey:@"specAttributes"];
        [postDic setObject:@"0" forKey:@"maxPrice"];
        [postDic setObject:@"0" forKey:@"minPrice"];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
            NSDictionary *ret = [SendService GetSearchProducts:postDic];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSLog(@"ret %@",ret);
                if (ret !=nil)
                {
                    if (pageForNumber == 1)
                    {
                        if (fListArray != nil)
                        {
                            [fListArray removeAllObjects];
                            fListArray = nil;
                        }
                        fListArray = [[NSMutableArray alloc] init];
                        if (sxListArray != nil)
                        {
                            [sxListArray removeAllObjects];
                            sxListArray = nil;
                        }
                        sxListArray = [[NSMutableArray alloc] init];
                    }
                    for (NSDictionary *pic in [[ret objectForKey:@"Entity"] objectForKey:@"ProductList"])
                    {
                        [fListArray addObject:pic];
                    }
                    
                    if (![[NSString  stringWithFormat:@"%@",[[ret objectForKey:@"Entity"] objectForKey:@"specAttributeList"]] isEqualToString:@"<null>"])
                    {
                        for (NSDictionary *pic in [[ret objectForKey:@"Entity"] objectForKey:@"specAttributeList"])
                        {
                            [sxListArray addObject:pic];
                        }
                    }

                }
                if (pageForNumber ==1)
                    [mTableView.header endRefreshing];
                else
                    [mTableView.footer endRefreshing];
                [mTableView reloadData];
                
            });
        });
        
    }
    else
    {
        [mTableView.footer noticeNoMoreData];
        [mTableView reloadData];
    }
    
}

-(void)barView
{
    UIView *bView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, screenMySize.size.width, 40)];
    bView.backgroundColor = [UIColor colorWithWhite:.9 alpha:1];
    [self.view addSubview:bView];
    
    NSArray *tArray = [NSArray arrayWithObjects:@"综合",@"销量",@"价格",@"筛选", nil];
    for (int i = 0; i < 4; i ++)
    {
        NSString *title = [tArray objectAtIndex:i];
        UIImage *imageD = nil;
        if (i == 0)
            imageD = [UIImage imageNamed:@"ssup_arrow"];
        else if (i == 1)
            imageD = [UIImage imageNamed:@""];
        else if (i == 2)
            imageD = [UIImage imageNamed:@"ssup&down"];
        else if (i == 3)
            imageD = [UIImage imageNamed:@"sssx"];
        CGSize titleSize = [title sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"Arial" size:labelSize-1]}];
        
        UIButton *inButton = [UIButton buttonWithType:UIButtonTypeCustom];
        CGRect frame = CGRectMake(0,0, screenMySize.size.width/4, 40);
        [inButton setImage:imageD forState:UIControlStateNormal];
        [inButton setFrame:frame];
        [inButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -imageD.size.width, 0, imageD.size.width)];
        [inButton setImageEdgeInsets:UIEdgeInsetsMake(0, titleSize.width, 0, -titleSize.width)];
        
        [inButton setTitle:title forState:UIControlStateNormal];
        if (i !=1)
        [inButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        else
            [inButton setTitleColor:[UIColor colorWithRed:243/255.0 green:125/255.0 blue:125/255.0 alpha:1] forState:UIControlStateNormal];
        inButton.titleLabel.font = [UIFont fontWithName:@"Arial" size:labelSize-1];
        inButton.center = CGPointMake(screenMySize.size.width*i/4+screenMySize.size.width/8, 64+40/2);
        inButton.tag = topButtonTag+i;
        [inButton addTarget:self action:@selector(aInBction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:inButton];
    }
    
}

-(void)aInBction:(id)sender
{
    int topType = ((UIButton*)sender).tag - topButtonTag;
    UIButton *topButton = (UIButton*)sender;
    
    if (topType != 3)
    {
        for (int i = 0; i < 3; i ++)
        {
            UIButton *btButton = (UIButton*)[self.view viewWithTag:topButtonTag+i];
            if (i == topType)
            {
                [btButton setTitleColor:[UIColor colorWithRed:243/255.0 green:125/255.0 blue:125/255.0 alpha:1] forState:UIControlStateNormal];
            }
            else
            {
                [btButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            }
        }
        
        if (topType != 0)
        {
            UIButton *btButton = (UIButton*)[self.view viewWithTag:topButtonTag];
            [btButton setImage:[UIImage imageNamed:@"ssup_arrow"] forState:UIControlStateNormal];
        }
        if (topType != 2)
        {
            UIButton *btButton = (UIButton*)[self.view viewWithTag:topButtonTag+2];
            [btButton setImage:[UIImage imageNamed:@"ssup&down"] forState:UIControlStateNormal];
        }
        if (topType == 2)
        {
            if (priceInt) {
                [topButton setImage:[UIImage imageNamed:@"ssup1"] forState:UIControlStateNormal];
            }
            else
                [topButton setImage:[UIImage imageNamed:@"ssdown1"] forState:UIControlStateNormal];
            priceInt = !priceInt;
        }
    }
    
    if (topType == 0)
    {
        if(dropDown == nil)
        {
            CGFloat f = 120;
            
            dropDown = [[NIDropDown alloc] initShowDropDown:sender setH:&f setA:[NSArray arrayWithObjects:@"综合",@"新品",@"评论数", nil]];
            dropDown.delegate = self;
        }
        else {
            [dropDown hideDropDown:sender];
            [self rel];
        }
        [topButton setImage:[UIImage imageNamed:@"ssup_down_rpress"] forState:UIControlStateNormal];
    }
    else
    {
        [self rel];
        if (topType ==1)
        {
            orderBy = 17;
            [mTableView.header beginRefreshing];
        }
        else if (topType ==2)
        {
            if (priceInt)
                orderBy = 11;
            else
                orderBy = 10;
            [mTableView.header beginRefreshing];
        }
        else if (topType ==3)
        {
            JKSideSlipView *oneSl = (JKSideSlipView*)[[UIApplication sharedApplication].keyWindow viewWithTag:2];
            if (oneSl != nil) {
                 [oneSl removeFromSuperview];
                oneSl = nil;
            }
            screenOneView *screenOne = [[screenOneView alloc] initWithFrame:CGRectMake(0, 0, SLIP_WIDTH, screenMySize.size.height)];
            screenOne.sxListArray = sxListArray;
            screenOne.delegate = self;
            //侧栏
            JKSideSlipView *_sideSlipView = [[JKSideSlipView alloc]initWithSender:self];
            _sideSlipView.backgroundColor = [UIColor clearColor];
            [_sideSlipView setContentView:screenOne];
            _sideSlipView.tag = 2;
            [[UIApplication sharedApplication].keyWindow addSubview:_sideSlipView];
             [_sideSlipView hide];
        }
    }
}

-(void)JKSshow
{
    JKSideSlipView *oneSl = (JKSideSlipView*)[[UIApplication sharedApplication].keyWindow viewWithTag:2];
    if (oneSl != nil) {
        [oneSl show];
    }
    [mTableView.header beginRefreshing];
}

- (void)niDropDownDelegateMethod: (NIDropDown *)sender aType:(int)aType
{
    NSArray *tarray = [NSArray arrayWithObjects:@"综合",@"新品",@"评论数", nil];
    UIButton *topButton = (UIButton*)[self.view viewWithTag:topButtonTag];
    
    NSString *title = [tarray objectAtIndex:aType];
    UIImage *imageD = [UIImage imageNamed:@"ssup_arrow"];

    CGSize titleSize = [title sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"Arial" size:labelSize-1]}];
    [topButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -imageD.size.width, 0, imageD.size.width)];
    [topButton setImageEdgeInsets:UIEdgeInsetsMake(0, titleSize.width, 0, -titleSize.width)];
    
    if (aType == 0)
        orderBy = 0;
    else  if (aType == 1)
        orderBy = 16;
    else if (aType == 2)
        orderBy = 18;
    [mTableView.header beginRefreshing];
    [self rel];
    
}
-(void)rel{
    if(dropDown != nil)
    {
        [UIView animateWithDuration:.5 animations:^{
            dropDown.alpha = 0;
        } completion:^(BOOL finished) {
            [dropDown removeFromSuperview];
            dropDown = nil;
        }];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return fListArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 40+screenMySize.size.height/4;
    }
    return screenMySize.size.height/4;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"search";
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        aTableView.showsVerticalScrollIndicator = NO;
    }
    cell.backgroundColor = [UIColor colorWithWhite:.95 alpha:1];
    int i = (int)[[cell.contentView subviews] count] - 1;
    for(;i >= 0 ; i--)
    {
        [[[cell.contentView subviews] objectAtIndex:i] removeFromSuperview];
    }
    return [self mCell:cell bCTableView:aTableView cellForRowAtIndexPath:indexPath];
    return cell;
}

- (UITableViewCell *)mCell:(UITableViewCell*)cell bCTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int  hightInt = 0;
    if (indexPath.row == 0)
    {
        hightInt = 40;
        
        
        NSString *title = @"查看大促商品";
        UIImage *imageD = [UIImage imageNamed:@""];

        CGSize titleSize = [title sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"Arial" size:labelSize-1]}];
        
        UIButton *inButton = [UIButton buttonWithType:UIButtonTypeCustom];
        CGRect frame = CGRectMake(0,0, screenMySize.size.width/2, 30);
        [inButton setImage:imageD forState:UIControlStateNormal];
        [inButton setFrame:frame];
        [inButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -imageD.size.width, 0, imageD.size.width)];
        [inButton setImageEdgeInsets:UIEdgeInsetsMake(0, titleSize.width, 0, -titleSize.width)];
        
        [inButton setTitle:title forState:UIControlStateNormal];
        [inButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        inButton.titleLabel.font = [UIFont fontWithName:@"Arial" size:labelSize-1];
        inButton.center = CGPointMake(screenMySize.size.width/2, 40/2);
        [inButton addTarget:self action:@selector(cxBction) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:inButton];
        
    }
    NSDictionary *dic = [fListArray objectAtIndex:indexPath.row];
    
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(30,10+hightInt, 100, screenMySize.size.height/4-20)];
    [bgImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[[dic objectForKey:@"DefaultPictureModel" ] objectForKey:@"ImageUrl"]]]];
    bgImageView.contentMode = UIViewContentModeScaleToFill;
    bgImageView.clipsToBounds  = YES;
    bgImageView.backgroundColor = [UIColor whiteColor];
    [cell.contentView addSubview:bgImageView];
    
    [cell.contentView addSubview:[self setFrame:CGRectMake(140, 10+hightInt, screenMySize.size.width-150, 65) setTitle:[NSString stringWithFormat:@"%@",[dic objectForKey:@"Name"]] setFont:labelSize setColor:[UIColor blackColor]]];
    
    [cell.contentView addSubview:[self setFrame:CGRectMake(140, screenMySize.size.height/4+hightInt-50, screenMySize.size.width-150, 20) setTitle:[NSString stringWithFormat:@"%@",[[dic objectForKey:@"ProductPrice"] objectForKey:@"Price"]] setFont:labelSize-2 setColor:[UIColor colorWithRed:241/255.0 green:83/255.0 blue:83/255.0 alpha:1]]];
    
    
    [cell.contentView addSubview:[self setFrame:CGRectMake(140, screenMySize.size.height/4+hightInt-30, screenMySize.size.width-150, 20) setTitle:[NSString stringWithFormat:@"好评%@人",[[dic objectForKey:@"ReviewOverviewModel"]objectForKey:@"TotalReviews" ]] setFont:labelSize-2 setColor:[UIColor blackColor]]];
    
    return cell;
}

-(UILabel*)setFrame:(CGRect)frame setTitle:(NSString*)title setFont:(int)font setColor:(UIColor*)myColor
{
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:frame];
    if (title != nil)
        titleLabel.text = [NSString stringWithFormat:@"%@",title];
    titleLabel.textAlignment = 0;
    titleLabel.numberOfLines = 0;
    titleLabel.font = [UIFont fontWithName:@"Arial" size:font];
    titleLabel.textColor = myColor;
    return titleLabel;
}

#pragma mark 大促销
-(void)cxBction
{
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    GoodsDetailsViewController *details = [[GoodsDetailsViewController alloc] init];
    details.productId = [NSString stringWithFormat:@"%@",[[[fListArray objectAtIndex:indexPath.row] objectForKey:@"ReviewOverviewModel"] objectForKey:@"ProductId"]];
    details.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:details animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
